package com.dayu.web.controller.system;

import java.util.*;

import com.dayu.common.core.redis.RedisCache;
import com.dayu.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.dayu.common.constant.Constants;
import com.dayu.common.core.domain.AjaxResult;
import com.dayu.common.core.domain.entity.SysMenu;
import com.dayu.common.core.domain.entity.SysUser;
import com.dayu.common.core.domain.model.LoginBody;
import com.dayu.common.core.domain.model.LoginUser;
import com.dayu.common.utils.ServletUtils;
import com.dayu.security.web.service.SysLoginService;
import com.dayu.security.web.service.SysPermissionService;
import com.dayu.framework.TokenService;
import com.dayu.system.service.ISysMenuService;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 验证是否重复登录
     * @return
     */
    @PostMapping("/repeat/login")
    public AjaxResult repeatLogin(HttpServletRequest request)
    {
        String tokenKey = tokenService.getDecryptToken(request);
        Map<String, Object> respMap = new HashMap<>();
        respMap.put("bool", false);
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser redisUser = redisCache.getCacheObject(key);
            if(user.getUserName().equals(redisUser.getUsername()) && !tokenKey.equals(key)) {
                respMap.put("bool", true);
            }
        }
        return AjaxResult.success(respMap);
    }

    /**
     * 强制退出 其它同一账户登录
     * @param request
     * @return
     */
    @PostMapping("/force/logout")
    public AjaxResult forceLogout(HttpServletRequest request) {
        String tokenKey = tokenService.getDecryptToken(request);
        List<String> outKeys = new ArrayList<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser redisUser = redisCache.getCacheObject(key);
            if(user.getUserName().equals(redisUser.getUsername()) && !tokenKey.equals(key)) {
                outKeys.add(key);
            }
        }
        for(String key: outKeys) {
            redisCache.deleteObject(key);
        }
        return AjaxResult.success();
    }

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
